package org.ran.demo.http.body;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.ran.demo.http.util.FileUtil;
import org.ran.demo.http.util.StreamUtil;

/**
 * 获取请求体或者响应体之后的处理方式
 * @author caoran
 *
 */
public class ContentType {
    public static void main(String[] args) throws Exception {
        try (ServerSocket serverSocket = new ServerSocket();) {
            serverSocket.bind(new InetSocketAddress(8080));
            while (true) {
                try {
                    Socket socket = serverSocket.accept();
                    OutputStream out = socket.getOutputStream();
                    InputStream in = socket.getInputStream();
                    String requestLine = StreamUtil.readLine(in);
                    System.out.println("请求方式和url为："+requestLine);
                    int length = 0;
                    String contentType = null;
                    while (true) {
                        String h = StreamUtil.readLine(in);
                        if (h.isEmpty()) {
                            break;
                        }
                        String[] header = h.split(":");
                        if (header[0].equals("Content-Length")) {
                            length = Integer.parseInt(header[1].trim());
                        }else if (header[0].equals("Content-Type")){
                            contentType = header[1].trim();
                        }
                    }
                    StreamUtil.readLength(in, length);
                    System.out.println(contentType);
                    out.write(Files.readAllBytes(Paths.get(FileUtil.RESPONSE_HEADER)));
                    out.write(Files.readAllBytes(Paths.get(FileUtil.RESPONSE_BODY)));
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
            }
        }
    }
}
